<template>
  <div class="login-container relative" v-loading="yzyToken">
    <div
      class="fixed family-hzgb login-title flex align-center"
      v-loading="yzyToken"
    >
      <!-- <img src="/fabu-admin/imgs/gk_logo.png" style="height:45px" alt="" /> -->
      <span class="mrl10">{{ title }}</span>
    </div>
    <div class="flex align-center login-box" v-loading="yzyToken">
      <div>
        <!-- <img src="/fabu-admin/uiImgs/login/pic.jpg" alt="" /> -->
      </div>
      <div class="login-panel ">
        <div class="title">
          <!-- <div class="titleDeco" /> -->
          <div class="titleText">欢迎回来</div>
          <!-- <div class="titleDeco" /> -->
        </div>
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form "
          label-position="right"
        >
          <el-form-item :error="loginForm.usernameError" label="" prop="name">
            <el-input
              class="input"
              prefix-icon="el-icon-user"
              ref="name"
              @change="loginForm.usernameError = ''"
              v-model="loginForm.name"
              placeholder="请输入用户名"
              name="name"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>
          <el-form-item :error="loginForm.passwordError" label="" prop="pwd">
            <el-input
              class="input"
              prefix-icon="el-icon-lock"
              :key="passwordType"
              ref="pwd"
              v-model="loginForm.pwd"
              :type="passwordType"
              @change="loginForm.passwordError = ''"
              placeholder="请输入密码"
              name="pwd"
              tabindex="2"
              autocomplete="on"
              @keyup.enter.native="handleLogin()"
            />
          </el-form-item>
          <el-form-item :error="loginForm.textError" v-if="captcha" prop="text">
            <div class="capchat">
              <el-input
                class="input"
                v-model="loginForm.text"
                @change="loginForm.textError = ''"
                @keyup.enter.native="handleLogin()"
                style="width: 120px; margin-right: 15px"
              />
              <div
                class="img"
                :style="{ backgroundImage: `url(${captcha})` }"
              />
              <el-button type="text" style="font-size: 14px" @click="getCaptcha"
                >换一组</el-button
              >
            </div>
          </el-form-item>
          <el-button
            class="logBtn"
            :loading="loading"
            type="primary"
            style="width: 100%; margin-bottom: 30px"
            @click.native.prevent="handleLogin()"
          >
            登录
          </el-button>
          <!-- <div
            class="text-right size14 pointer color-active"
            style="margin-top:-20px"
            @click="goYuezhengyi"
          >
            粤政易登录
          </div> -->
        </el-form>
      </div>
    </div>

    <!-- 默认登录修改密码 -->
    <el-dialog
      :close-on-click-modal="false"
      width="40%"
      :visible.sync="editDialog"
      :append-to-body="true"
      v-loading="editLoading"
      v-dialogDrag
      custom-class="widget-dialog widget-search center no-margin "
      title="监测到你当前密码未做修改，建议先修改密码再进行登录!"
    >
      <form-create
        v-model="editFormInstance"
        :value.sync="editData"
        :rule="editRule"
        :option="editOptions"
      />
      <template slot="footer">
        <div class="text-center">
          <el-button
            size="mini"
            type="primary"
            @click="updatePassword(editData)"
            >确认修改</el-button
          >
        </div>
        <!--         
        <el-button size="mini" @click="setGo(userData, resData)"
          >暂不修改</el-button
        > -->
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  sysLogin as login,
  sysGetRoleByUserId,
  sysEditUser as updateApi //更新、新增数据的api
} from "@/api";
import { title } from "@/configurations.js";
import rootUrl from "@/api/request/url";
import random from "lodash/random";
import md5 from "js-md5";
import { getBase64Image } from "@/utils/imgTools";
import Cookies from "js-cookie";
import { newPassword } from "@/formRules/system/UserViewRules";
import { editFormOptions } from "@/formRules";
import autofit from "autofit.js";
export default {
  name: "Login",
  data() {
    return {
      title,
      animationClass: "",
      loginForm: {
        // username: "",
        usernameError: "",
        // password: "",
        passwordError: "",
        text: "",
        textError: "",
        name: "",
        pwd: ""
      },
      loginRules: {
        name: [
          {
            required: true,
            trigger: "blur",
            message: "请输入用户名进行登录"
          }
        ],
        pwd: [
          {
            required: true,
            trigger: "blur",
            message: "请输入密码进行登录"
          }
        ],
        text: [{ required: true, trigger: "blur", message: "请输入验证码" }]
      },
      captcha: "",
      passwordType: "password",
      loading: false,
      otherQuery: {},
      editData: {},
      editFormInstance: {},
      editOptions: editFormOptions(),
      userData: {},
      editRule: newPassword(),
      resData: {},
      editDialog: false,
      loginParam: {},
      editLoading: false
    };
  },
  computed: {},
  created() {
    this.getCaptcha();
  },
  destroyed() {
    autofit.off();
  },
  mounted() {
    autofit.init();
  },
  methods: {
    getCaptcha() {
      getBase64Image(`${rootUrl}/sys/getCode?id=${random(1, 100)}`).then(
        res => {
          this.captcha = res;
        }
      );
    },
    async updatePassword() {
      if (!this.validation()) return false;
      let params = {
        ...this.userData
      };
      params.userPwd = this.editData.password;
      if (!params.userPwd) {
        this.$notified.error({
          message: "请先输入密码！"
        });
        return false;
      }
      if (params.userPwd == "Aazhcs#123456") {
        this.$notified.error({
          message: "不建议新密码与原始密码一致，请重新输入！"
        });
        return false;
      }
      this.editLoading = true;
      let { data, msg, code } = await updateApi(params).finally(
        () => (this.editLoading = false)
      );
      if (code == 200) {
        this.loginForm.pwd = this.editData.password;
        this.$notify({
          title: "密码修改成功",
          message: "即将自动登录...",
          type: "success"
        });
        this.$nextTick(() => {
          this.handleLogin();
        });
      } else {
        this.$notified.error({
          message: msg
        });
      }
    },
    handleLogin(hasToken) {
      console.log("hasToken--");
      console.log(hasToken);
      if (hasToken) {
        let params = {
          token: this.yzyToken
        };
        login(params)
          .then(res => {
            if (res.code == 200) {
              let userData = res.data.sysUser;
              //赋值角色
              sysGetRoleByUserId({ userId: userData.id }).then(({ data }) => {
                this.userData = res.data.sysUser;
                this.resData = res;
                if (
                  !Number(this.userData.isEdit) &&
                  this.userData.roleId == 15
                ) {
                  this.editDialog = true;
                } else {
                  this.setGo(this.userData, res);
                }
              });
            } else {
              this.$notified.error({
                message: res.msg
              });
            }
            this.loading = false;
          })
          .catch(err => {
            this.loading = false;
          });
        return;
      }
      if (!this.captcha) {
        this.getCaptcha();
        return;
      }
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          let param = {
            code: this.loginForm.text,
            pwd: md5(this.loginForm.pwd),
            userName: this.loginForm.name
          };
          this.loginParam = param;
          login(param)
            .then(res => {
              if (res.code == 200) {
                let userData = res.data.sysUser;
                //赋值角色
                sysGetRoleByUserId({ userId: userData.id }).then(({ data }) => {
                  // userData.role = {
                  //   id: 1,
                  //   roleName: "",
                  // };
                  this.userData = res.data.sysUser;
                  this.resData = res;
                  //   return;
                  if (
                    !Number(this.userData.isEdit) &&
                    this.userData.roleId == 15
                  ) {
                    this.editDialog = true;
                  } else {
                    this.setGo(this.userData, res);
                  }
                });
              } else {
                this.getCaptcha();
                this.$notified.error({
                  message: res.msg
                });
              }
              this.loading = false;
            })
            .catch(err => {
              switch (err.code) {
                case 501:
                  this.loginForm.usernameError = "用户名未注册";
                  break;
                case 502:
                  this.loginForm.passwordError = "密码错误";
                  break;
                case 503:
                  this.loginForm.textError = "请正确输入验证码";
                  break;
              }
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    setGo(userData, res) {
      //赋值角色
      sysGetRoleByUserId({ userId: userData.id }).then(({ data }) => {
        Cookies.set("isAdmin", "false", { expires: 3 });
        if (data[0]?.id == 1) {
          //管理全部权限
          Cookies.set("isAdmin", "true", { expires: 3 });
        }
        userData.role = data[0];
        Cookies.set("logined_xinxifabu", "true", { expires: 3 });
        Cookies.set("userNow", JSON.stringify(userData), {
          expires: 3
        });
        if (res?.data?.sysMenuList?.length == 0) {
          this.$message.error("当前用户暂无访问权限，请联系管理员配置权限!");
          return false;
        }

        this.$notified.success({
          message: "登录成功！"
        });
        console.log(res.data.sysMenuList);
        localStorage.setItem(
          "sysMenuList_xinxifabu",
          JSON.stringify(res.data.sysMenuList)
        );
        // return;
        this.$nextTick(() => {
          // setAddRoutes();
          window.location.href = `${document.location.protocol}//${
            window.location.hostname
          }${
            window.location.port ? ":" + window.location.port : ""
          }/fabu-admin/`;
          setTimeout(() => {
            window.location.reload();
          }, 500);
        });
      });
    },
    /**
     * @name 表单验证
     * @description 如果有则在此处写入逻辑
     * @returns {Boolean} 表单验证结果
     */
    validation() {
      let satate = false;
      this.editFormInstance.validate((valid, fail) => {
        satate = valid;
      });
      // return true;
      return satate;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.login-container {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  background: linear-gradient(0deg, #ffffff 10%, #91cdff 100%);
  background-color: var(--color-primary);

  background-size: 100% 100%;
  .login-title {
    top: 15%;
    left: 50%;
    color: #2478ce;
    font-size: 40px;
    transform: translateX(-50%);
  }
  .login-box {
    box-shadow: 0 0 11px $--color-primary;
    position: fixed;
    top: 24%;
    max-height: 433px;
    overflow: hidden;
  }
  .login-panel {
    display: flex;
    flex-direction: column;
    justify-content: center;
    // margin-left: 50px;
    height: 435px;
    width: 434px;
    // top: -50px;
    align-items: center;
    flex-shrink: 0;
    position: relative;
    background-color: $--background-color-base;
    border-radius: $--border-radius-base;
    padding: 16px;

    .title {
      //   width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 33px;
      user-select: none;
      color: $--color-text-primary;
      .titleText {
        font-size: 26px;
        font-weight: 600;
        position: relative;
        margin: 0px 11px;
        flex-shrink: 0;
        border-bottom: 4px solid #d5010f;
        padding-bottom: 6px;
        color: $--color-primary;
      }
      .titleDeco {
        min-width: 79px;
        height: 2px;
        flex-grow: 1;
        background: linear-gradient(270deg, #0066ff, #15baff);
      }
    }
    .login-form {
      width: 70%;
      .capchat {
        display: flex;
        .img {
          height: 28px;
          width: 80px;
          background-size: 100% 100%;
          margin-right: 16px;
        }
      }
    }
  }
}
</style>
